package day240729.project;



import day240729.dto.CustomResult;
import day240729.project.download.Downloader;
import day240729.project.notificator.NopeNotificator;
import day240729.project.notificator.Notificator;
import day240729.project.parser.Parser;
import day240729.project.repository.Repository;
import day240729.project.util.MyEmailUtil;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

public class App {
    public static final Properties PROPERTIES;

    static {
        // 读取配置文件，获取整个程序需要的全局配置信息
        PROPERTIES = loadFromConfiguration();

        // 初始化
        init();
    }
    private static void init() {
        // Email 相关设置
        MyEmailUtil.FROM = PROPERTIES.getProperty("from");
        MyEmailUtil.SECRET_TOKEN = PROPERTIES.getProperty("secret_token");
    }

    public static void main(String[] args) throws Exception {

        // === --- ===
        //=== === ===
        //定义规范（Boss视角）
        //定义规范的具体落地（黑盒子的思想）：
        //downloader
        //Downloader downloader = Downloader.getDownloader(properties.getProperty("downloader"));
        /*Downloader downloader = MyReflectUtil.getInstance(properties.getProperty("downloader"));
        String html = downloader.download(properties.getProperty("url"));
        System.out.println(html);
        System.out.println("Downloader - 下载完成");*/
        String url = PROPERTIES.getProperty("url");
        System.out.println("Downloader - 正在下载...：" + url);
        String html = Downloader.getInstance().download(url);
        //System.out.println(html);
        System.out.println("Downloader - 下载完成！");
        // Parser
        System.out.println("Parser - 正在解析...");
        List<CustomResult> results = Parser.getInstance().parse(html);
        //System.out.println(results);
        System.out.println("Parser - 解析完成！(共获取到" + results.size() + "条数据)");
        //Repository
        System.out.println("Repository - 正在储存");
        Repository.getInstance().store(results);
        System.out.println("Repository - 储存完成");
        //Notificator
        System.out.println("Notificator - 正在通知");
        Notificator.notice(results);
        //System.out.println("Notificator - 通知完成");


    }

    private static Properties loadFromConfiguration() {
        Properties properties = new Properties();
        String fileName = "ice1/src/day240729/project/config.properties";
        try {
            properties.load(new FileReader(fileName));
        } catch (FileNotFoundException e) {
            System.out.println("配置文件[" + fileName + "]不存在。");
            throw new RuntimeException(e);
        } catch (IOException e) {
            System.out.println("未知的错误！");
            throw new RuntimeException(e);
        }
        //System.out.println(properties);
        System.out.println("配置文件读取成功");
        return properties;
    }
}